import { useState, useEffect } from 'react';
import { useParams } from 'react-router-dom';
import { getPost } from '../services/api';
import Vote from '../components/Vote';
import AskPost from '../components/AskPost';
import { ChatBubbleLeftRightIcon } from '@heroicons/react/24/outline';

interface Post {
  ID: number;
  title: string;
  content: string;
  CreatedAt: string;
  upvote_count: number;
  downvote_count: number;
}

export default function PostPage() {
  const [post, setPost] = useState<Post | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isAskPostVisible, setIsAskPostVisible] = useState(false);
  const { postId } = useParams<{ postId: string }>();

  useEffect(() => {
    const fetchPost = async () => {
      if (!postId) return;
      try {
        setLoading(true);
        const fetchedPost = await getPost(postId);
        setPost(fetchedPost);
      } catch (err) {
        setError('Failed to fetch post');
        console.error(err);
      } finally {
        setLoading(false);
      }
    };

    fetchPost();
  }, [postId]);

  if (loading) {
    return <div>Loading...</div>;
  }

  if (error) {
    return <div>{error}</div>;
  }

  if (!post) {
    return <div>Post not found</div>;
  }

  return (
    <div className="relative isolate overflow-hidden bg-white px-6 py-24 sm:py-32 lg:overflow-visible lg:px-0 dark:bg-gray-900">
      <div className="absolute inset-0 -z-10 overflow-hidden">
        <svg
          aria-hidden="true"
          className="absolute top-0 left-[max(50%,25rem)] h-256 w-512 -translate-x-1/2 mask-[radial-gradient(64rem_64rem_at_top,white,transparent)] stroke-gray-200 dark:stroke-gray-800"
        >
          <defs>
            <pattern
              x="50%"
              y={-1}
              id="e813992c-7d03-4cc4-a2bd-151760b470a0"
              width={200}
              height={200}
              patternUnits="userSpaceOnUse"
            >
              <path d="M100 200V.5M.5 .5H200" fill="none" />
            </pattern>
          </defs>
          <svg x="50%" y={-1} className="overflow-visible fill-gray-50 dark:fill-gray-800/50">
            <path
              d="M-100.5 0h201v201h-201Z M699.5 0h201v201h-201Z M499.5 400h201v201h-201Z M-300.5 600h201v201h-201Z"
              strokeWidth={0}
            />
          </svg>
          <rect fill="url(#e813992c-7d03-4cc4-a2bd-151760b470a0)" width="100%" height="100%" strokeWidth={0} />
        </svg>
      </div>
      <div className="mx-auto max-w-2xl text-center lg:max-w-4xl">
        <h1 className="mt-2 text-4xl font-semibold tracking-tight text-pretty text-gray-900 sm:text-5xl dark:text-white">
          {post.title}
        </h1>
      </div>
      <div className={`mx-auto mt-16 ${isAskPostVisible ? 'max-w-7xl grid grid-cols-1 gap-x-8 lg:grid-cols-3' : 'max-w-2xl text-left lg:max-w-4xl'}`}>
        <div className={isAskPostVisible ? 'lg:col-span-2' : ''}>
          <div className="flex items-center gap-x-4">
              <Vote postId={post.ID} initialUpvotes={post.upvote_count} initialDownvotes={post.downvote_count} />
          </div>
          <div className="text-base/7 text-gray-600 dark:text-gray-400 mt-8 whitespace-pre-wrap">
            {post.content}
          </div>
        </div>
        {isAskPostVisible && (
          <div className="lg:sticky lg:top-24 lg:h-screen">
            <div className="mt-12 border-t border-gray-200 dark:border-gray-700 pt-8 lg:mt-0 lg:border-0 lg:pt-0">
              <AskPost postId={post.ID.toString()} />
            </div>
          </div>
        )}
      </div>
      <button 
        onClick={() => setIsAskPostVisible(!isAskPostVisible)}
        className="fixed bottom-8 right-8 flex items-center gap-x-2 rounded-full bg-indigo-600 p-4 text-sm font-semibold text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600 dark:bg-indigo-500 dark:hover:bg-indigo-400"
      >
        <ChatBubbleLeftRightIcon className="h-6 w-6" />
        <span className={isAskPostVisible ? '' : 'sr-only'}>Ask AI</span>
      </button>
    </div>
  )
}